<template>
  <div class="app-container">
    <!-- 操作按钮区域 -->
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>材料领用单</h3>
      <el-button size="small" type="success" @click="handleAdd">
        <i class="el-icon-plus" />
        新增
      </el-button>
    </div>
    <!-- 自定义下划线，替代el-divider -->
    <div class="custom-divider" />
    <!-- <el-card>
      <div class="table-operations-wrapper">
        <div class="table-operations">
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >
            {{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            ></i>
          </el-button>
          <el-button size="small" type="success" @click="handleAdd">
            <i class="el-icon-plus"></i>
            新增
          </el-button>
          <el-button type="warning" size="small" @click="handleEdit">
            <i class="el-icon-edit"></i>
            修改
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete">
            <i class="el-icon-delete"></i>
            批量删除
          </el-button>
        </div>
      </div>
    </el-card> -->

    <!-- 搜索区域使用 transform 包裹 -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <el-form
          ref="searchForm"
          :model="listQuery"
          :inline="true"
          label-width="90px"
        >
          <el-form-item label="状态">
            <el-select v-model="listQuery.status" placeholder="请选择状态">
              <!-- <el-option :label="全部" :value="0"></el-option> -->
              <el-option label="待处理" :value="0"></el-option>
              <el-option label="已处理" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型:">
            <el-select v-model="listQuery.type" placeholder="请选择类型">
              <el-option :label="日常领料" :value="1"></el-option>
              <el-option :label="工程领料" :value="2"></el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="商品:">
            <el-select
              v-model="listQuery.goodsId"
              placeholder="请选择商品"
              clearable
              style="width: 200px"
              @change="handleGoodsChange"
            >
              <el-option
                v-for="item in goodsList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->

          <!-- <el-form-item label="供应商:">
            <el-select
              v-model="listQuery.supplierId"
              placeholder="请选择供应商"
              clearable
              style="width: 200px"
              @change="handleSupplierChange"
            >
              <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item label="申请时间:">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              style="width: 350px"
              @change="handleDateChange"
            />
          </el-form-item>

          <!-- <el-form-item label="仓库:">
            <el-select
              v-model="listQuery.warehouseId"
              placeholder="请选择仓库"
              clearable
              style="width: 200px"
              @change="handleWarehouseChange"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="状态:">
            <el-select
              v-model="listQuery.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" />
              <el-option label="待处理" :value="0" />
              <el-option label="已处理" :value="1" />
              <el-option label="已驳回" :value="-1" />
            </el-select>
          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-collapse-transition>

    <!-- 表格区域 -->
    <div class="table-operations-wrapper">
      <div class="table-operations">
        <!-- <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >
            {{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            ></i>
          </el-button> -->
        <el-form
          ref="searchForm"
          :model="listQuery"
          :inline="true"
          label-width="80px"
        >
          <el-form-item label="负责人" prop="operatorId">
            <el-select
              v-model="listQuery.operatorId"
              placeholder="请选择负责人"
              filterable
              style="width: 100%"
              clearable
              @change="handleDirectorChange"
              @focus="onDirectorFocus"
            >
              <el-option
                v-for="item in directorList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="listQuery.status"
              placeholder="请选择状态"
              clearable
              @change="handelStatus"
            >
              <!-- <el-option :label="全部" :value="0"></el-option> -->
              <el-option label="待处理" :value="0"></el-option>
              <el-option label="已处理" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型:">
            <el-select
              v-model="listQuery.type"
              placeholder="请选择类型"
              clearable
              @change="handelType"
            >
              <el-option label="日常领料" :value="1"></el-option>
              <el-option label="工程领料" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="商品:">
            <el-select
              v-model="listQuery.goodsId"
              placeholder="请选择商品"
              clearable
              style="width: 200px"
              @change="handleGoodsChange"
            >
              <el-option
                v-for="item in goodsList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="供应商:">
            <el-select
              v-model="listQuery.supplierId"
              placeholder="请选择供应商"
              clearable
              style="width: 200px"
              @change="handleSupplierChange"
            >
              <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item label="申请时间:">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              style="width: 350px"
              @change="handleDateChange"
            />
          </el-form-item>

          <!-- <el-form-item label="仓库:">
            <el-select
              v-model="listQuery.warehouseId"
              placeholder="请选择仓库"
              clearable
              style="width: 200px"
              @change="handleWarehouseChange"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="状态:">
            <el-select
              v-model="listQuery.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" />
              <el-option label="待处理" :value="0" />
              <el-option label="已处理" :value="1" />
              <el-option label="已驳回" :value="-1" />
            </el-select>
          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- <el-button size="small" type="success" @click="handleAdd">
            <i class="el-icon-plus"></i>
            新增
          </el-button> -->
      </div>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="materialList"
      border
      style="width: 100%; margin-top: 20px"
    >
      <!-- <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column> -->
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column label="商品明细" width="230" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.list && scope.row.list.length > 0"
            class="goods-detail-container"
          >
            <!-- 循环渲染每个商品项 -->
            <div
              v-for="(item, index) in scope.row.list"
              :key="index"
              class="goods-item"
            >
              <div class="goods-row">
                <!-- 商品名称和数量 -->
                <div class="goods-name">{{ item.goodsName }}</div>
                <div class="goods-number">
                  数量: <span class="number-value">{{ item.number }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-goods">暂无商品</div>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" prop="goodsName" label="商品名称" /> -->
      <!-- <el-table-column
        prop="directorName"
        label="负责人"
        align="center"
      /> -->
      <el-table-column align="center" prop="type" label="类型" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type === 1 ? 'success' : 'warning'">{{
            scope.row.type === 1 ? "日常领料" : "工程领料"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="operatorName"
        label="操作人"
        width="120"
      />
      <el-table-column
        align="center"
        prop="directorName"
        label="负责人"
        width="120"
      />
      <el-table-column
        align="center"
        prop="projectName"
        label="工程名称"
        width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="createTime"
        label="申请时间"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            :disabled="scope.row.status === 1"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            :disabled="scope.row.status === 1"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="650px"
    >
      <el-form
        ref="dataForm"
        :model="materialForm"
        :rules="rules"
        label-width="80px"
        label-position="left"
      >
        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <div class="goods-table-container">
            <el-table
              :data="materialForm.list || []"
              border
              style="width: 100%"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            >
              <el-table-column label="商品名称" width="260">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'list.' + scope.$index + '.goodsId'"
                    :rules="{
                      required: true,
                      message: '请选择商品',
                      trigger: 'change',
                    }"
                    class="mb-0"
                  >
                    <el-select
                      v-model="scope.row.goodsId"
                      placeholder="请选择商品"
                      style="width: 100%"
                      filterable
                      clearable
                      @change="
                        (val) => handleGoodsItemChange(val, scope.$index)
                      "
                    >
                      <el-option
                        v-for="item in goodsList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                        <span style="float: left">{{ item.name }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="数量" width="150">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'list.' + scope.$index + '.number'"
                    :rules="{
                      required: true,
                      message: '请输入数量',
                      trigger: 'blur',
                    }"
                    class="mb-0"
                  >
                    <el-input-number
                      v-model="scope.row.number"
                      :min="1"
                      :precision="0"
                      placeholder="数量"
                      style="width: 100%"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click.prevent="removeGoodsItem(scope.$index)"
                  />
                </template>
              </el-table-column>
            </el-table>

            <div class="add-goods-btn">
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="addGoodsItem"
              >
                添加商品
              </el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 基本信息表单 -->
        <el-form-item label="类型" prop="type" class="is-required">
          <el-radio-group
            v-model="materialForm.type"
            @change="handleTypeChange"
          >
            <el-radio :label="1">
              <span style="color: #333">日常领料</span>
            </el-radio>
            <el-radio :label="2">
              <span style="color: #333">工程领料</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="负责人" prop="directorId">
          <el-select
            v-model="materialForm.directorId"
            placeholder="请选择负责人"
            filterable
            :disabled="materialForm.type !== 2"
            style="width: 100%"
            clearable
            @focus="onDirectorFocus"
          >
            <el-option
              v-for="item in directorList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="工程名称" prop="projectName">
          <el-input
            v-model="materialForm.projectName"
            :disabled="materialForm.type !== 2"
            placeholder="请输入工程名称"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="materialForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selMaterialRequisitionListApi,
  addMaterialRequisitionApi,
  updateMaterialRequisitionByIdApi,
  delMaterialRequisitionByIdApi,
} from "@/api/material";
import { selGoodsListApi } from "@/api/goods";
import {
  selSupplierListApi,
  selWarehouseListApi,
  selStaffListApi,
} from "@/api/system";
export default {
  name: "MaterialRequisition",
  filters: {
    parseTime(time) {
      return parseTime(time);
    },
  },
  data() {
    return {
      isFilterVisible: false,
      listLoading: false,
      // 查询参数 - 按照接口文档定义
      listQuery: {
        endTime: undefined, // 结束时间 integer(int64)
        operatorId: "",
        page: 1, // 当前页码 integer(int32)
        pageSize: 10, // 每页条数 integer(int32)
        startTime: undefined, // 开始时间 integer(int64)
        status: undefined, // 状态 integer(int32)
        type: undefined, // 类型 integer(int32)
        userId: this.$store.getters.userId,
      },
      dateRange: [], // 日期范围
      tableData: [], // 表格数据
      materialList: [], // 材料领用单列表
      total: 0, // 总条数
      directorList: [], // 负责人列表
      dialogFormVisible: false,
      // 表单数据 - 按照接口文档定义
      materialForm: {
        id: "", // ID，用于区分新增/编辑
        directorId: "", // 项目负责人Id - string
        operatorId: this.$store.getters.userId, // 操作人ID - string
        projectId: "", // 工程Id - string
        projectName: "", // 工程名称 - string
        remark: "", // 备注 - string
        type: 1, // 类型 1-日常领料 2-工程领料 - integer
        list: [
          {
            // 初始化为非空数组
            goodsId: "", // 物品ID - integer
            number: 1, // 数量 - integer
          },
        ],
      },
      goodsList: [], // 商品列表
      warehouseList: [], // 仓库列表
      supplierList: [], // 供应商列表
      // 商品查询参数
      goodsQuery: {
        goodsTypeId: null,
        page: 1,
        pageSize: 10,
        name: "",
        no: "",
        supplierId: null,
        warehouseId: null,
      },
      // 供应商列表查询参数
      supplierQuery: {
        page: 1,
        pageSize: 9999,
        name: "",
        supplierTypeId: "", // 供应商类型
      },
      // 仓库列表查询参数
      warehouseQuery: {
        page: 1,
        pageSize: 9999,
        name: "",
      },
      // 员工列表查询参数
      staffQuery: {
        page: 1,
        pageSize: 9999,
        name: "",
        mobile: "",
        parent: "",
      },
      // 商品查询参数
      goodsQuery: {
        goodsTypeId: null,
        name: "",
        page: 1,
        pageSize: 9999,
        supplierId: null,
        warehouseId: null,
      },
      staffList: [], // 员工列表
      // 表单验证规则
      rules: {
        directorId: [
          { required: false, message: "请选择负责人", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (this.materialForm.type === 2 && !value) {
                callback(new Error("工程领料时必须选择负责人"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
        number: [{ required: true, message: "请输入数量", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        projectName: [
          { required: false, message: "请输入工程名称", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (this.materialForm.type === 2 && !value) {
                callback(new Error("工程领料时必须填写工程名称"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        remark: [
          { max: 200, message: "长度不能超过200个字符", trigger: "blur" },
        ],
      },
      directorLoading: false,
    };
  },
  computed: {
    // 通过id判断是新增还是编辑
    dialogTitle() {
      return this.materialForm.id ? "编辑" : "新增";
    },
  },
  created() {
    this.selMaterialRequisition();
    this.selSupplierList();
    this.selWarehouseList();
    this.selStaffList();
    this.selGoodsList();
  },
  methods: {
    // 获取材料领用单列表数据
    async selMaterialRequisition() {
      try {
        this.listLoading = true;
        const res = await selMaterialRequisitionListApi(this.listQuery);
        this.materialList = res.records;
        this.total = res.total;
      } catch (error) {
        console.error("获取列表失败:", error);
        this.$message.error("获取列表失败");
      } finally {
        this.listLoading = false;
      }
    },
    // 状态改变
    handelStatus(val) {
      this.selMaterialRequisition();
    },
    // 类型改变
    handelType(val) {
      this.selMaterialRequisition();
    },
    // 获取供应商列表
    async selSupplierList() {
      const res = await selSupplierListApi(this.supplierQuery);
      this.supplierList = res.records;
    },
    // 获取仓库列表
    async selWarehouseList() {
      const res = await selWarehouseListApi(this.warehouseQuery);
      this.warehouseList = res.records;
    },
    // 获取员工列表
    async selStaffList() {
      const res = await selStaffListApi(this.staffQuery);
      this.staffList = res.records;
    },
    // 获取商品列表
    async selGoodsList() {
      const res = await selGoodsListApi(this.goodsQuery);
      this.goodsList = res.records || [];
    },
    // 负责人改变
    handleDirectorChange(val) {
      console.log(val);
      this.listQuery.page = 1;
      this.selMaterialRequisition();
    },
    // 商品改变
    handleGoodsChange(val) {
      console.log(val);
      this.selSupplierList();
    },
    // 供应商改变
    handleSupplierChange(val) {
      console.log(val);
      this.selWarehouseList();
    },
    // 仓库改变
    handleWarehouseChange(val) {
      console.log(val);
      this.selStaffList();
    },
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: "warning",
        1: "success",
      };
      return statusMap[status] || "info";
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: "待处理",
        1: "已处理",
      };
      return statusMap[status] || "未知状态";
    },

    // 日期改变
    handleDateChange(val) {
      if (val) {
        // 设置开始时间为当天的 00:00:00
        const startDate = new Date(val[0]);
        startDate.setHours(0, 0, 0, 0);
        this.listQuery.startTime = Math.floor(startDate.getTime() / 1000);

        // 设置结束时间为当天的 23:59:59
        const endDate = new Date(val[1]);
        endDate.setHours(23, 59, 59, 999);
        this.listQuery.endTime = Math.floor(endDate.getTime() / 1000);
      } else {
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.selMaterialRequisition();
    },

    // 重置查询
    resetFilter() {
      this.dateRange = [];
      this.listQuery = {
        endTime: null,
        operatorId: "",
        page: 1,
        pageSize: 10,
        startTime: null,
        status: null,
        type: null,
        userId: this.$store.getters.userId,
      };
      this.selMaterialRequisition();
    },

    // 每页条数改变
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.selMaterialRequisition();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.selMaterialRequisition();
    },

    // 审核
    handleReview(row) {
      // TODO: 实现审核逻辑
      console.log("审核:", row);
    },

    // 查看详情
    handleDetail(row) {
      // TODO: 实现查看详情逻辑
      console.log("查看详情:", row);
    },

    // 新增按钮点击
    handleAdd() {
      this.dialogFormVisible = true;
      this.dialogTitle = "新增领料单";
      this.editMode = false;

      // 重置表单
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields();
        this.materialForm = {
          id: "",
          directorId: "",
          operatorId: this.$store.getters.userId,
          projectId: "",
          projectName: "",
          remark: "",
          type: 1,
          list: [
            {
              // 初始化为非空数组
              goodsId: "",
              number: 1,
            },
          ],
        };
      });
    },

    // 打开编辑对话框
    handleEdit(row) {
      this.dialogFormVisible = true;
      this.dialogTitle = "编辑领料单";
      this.editMode = true;

      // 复制数据
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields();
        // 深拷贝防止直接修改原数据
        this.materialForm = JSON.parse(JSON.stringify(row));

        // 确保list存在
        if (!this.materialForm.list) {
          this.$set(this.materialForm, "list", []);
        }

        // 如果list为空，添加一个空商品项
        if (this.materialForm.list.length === 0) {
          this.materialForm.list.push({
            goodsId: "",
            number: 1,
          });
        }
      });
    },

    // 处理单行删除
    async handleDelete(id) {
      try {
        await this.$confirm("确认删除该材料领用记录?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const res = await delMaterialRequisitionByIdApi(id);
        if (res.code === 1) {
          this.$message.success("删除成功");
          this.selMaterialRequisition();
        } else {
          this.$message.error(res.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
      }
    },

    // 处理类型变更
    handleTypeChange(val) {
      if (val === 1) {
        // 切换到日常领料时清空工程相关字段和负责人
        this.materialForm.projectName = "";
        this.materialForm.projectId = "";
        this.materialForm.directorId = "";
      }
      // 重新验证表单
      this.$nextTick(() => {
        this.$refs["dataForm"].validateField(["projectName", "directorId"]);
      });
    },

    // 负责人选择获取焦点时加载数据
    onDirectorFocus() {
      this.directorLoading = true;
      this.searchDirectors("");
    },

    // 搜索负责人
    async searchDirectors(query) {
      try {
        const res = await selStaffListApi({
          page: 1,
          pageSize: 9999,
          name: query,
        });
        this.directorList = res.records || [];
      } catch (error) {
        console.error("搜索负责人失败:", error);
        this.$message.error("搜索负责人失败");
        this.directorList = [];
      } finally {
        this.directorLoading = false;
      }
    },

    // 提交表单
    submitForm() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          try {
            // 检查商品列表
            if (
              !this.materialForm.list ||
              this.materialForm.list.length === 0
            ) {
              this.$message.warning("请至少添加一项商品");
              return;
            }

            // 构建提交参数
            const params = {
              operatorId: this.$store.getters.userId, // 操作人ID
              type: this.materialForm.type, // 类型：1-日常领料 2-工程领料
              remark: this.materialForm.remark, // 备注
              list: this.materialForm.list.map((item) => ({
                goodsId: item.goodsId, // 物品ID
                number: item.number, // 数量
              })),
            };

            // 如果是工程领料，需要添加工程相关字段和负责人
            if (this.materialForm.type === 2) {
              if (!this.materialForm.directorId) {
                this.$message.warning("工程领料时必须选择负责人");
                return;
              }
              if (!this.materialForm.projectName) {
                this.$message.warning("工程领料时必须填写工程名称");
                return;
              }

              params.directorId = this.materialForm.directorId; // 项目负责人Id
              params.projectName = this.materialForm.projectName; // 工程名称
              params.projectId = this.materialForm.projectId || ""; // 工程Id，如果没有则传空字符串
            }

            // 根据是否有ID判断是新增还是编辑
            if (this.materialForm.id) {
              // 编辑操作
              params.id = this.materialForm.id;
              await updateMaterialRequisitionByIdApi(params);
              this.$message.success("修改成功");
            } else {
              // 新增操作
              await addMaterialRequisitionApi(params);
              this.$message.success("添加成功");
            }

            this.dialogFormVisible = false;
            this.selMaterialRequisition(); // 刷新列表
          } catch (error) {
            console.error("操作失败:", error);
            this.$message.error("操作失败: " + (error.message || "未知错误"));
          }
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },

    // 添加商品项
    addGoodsItem() {
      if (!this.materialForm.list) {
        this.$set(this.materialForm, "list", []);
      }
      this.materialForm.list.push({
        goodsId: "",
        number: 1,
      });
    },

    // 删除商品项
    removeGoodsItem(index) {
      if (this.materialForm.list.length > 1) {
        this.materialForm.list.splice(index, 1);
      } else {
        this.$message.warning("至少需要一项商品");
      }
    },

    // 处理商品选择变化
    handleGoodsItemChange(goodsId, index) {
      console.log("选择了商品ID:", goodsId, "索引:", index);
      const selectedGoods = this.goodsList.find((item) => item.id === goodsId);
      if (selectedGoods) {
        console.log("选择的商品:", selectedGoods);
        // 如果需要可以在这里处理其他逻辑
      }
    },

    // 验证商品列表
    validateGoodsList(rule, value, callback) {
      if (!value || value.length === 0) {
        return callback(new Error("请至少添加一项商品"));
      }

      for (let i = 0; i < value.length; i++) {
        const item = value[i];
        if (!item.goodsId) {
          return callback(new Error(`第${i + 1}项商品未选择商品`));
        }
        if (!item.number || item.number <= 0) {
          return callback(new Error(`第${i + 1}项商品未设置数量或数量无效`));
        }
      }

      callback();
    },

    // 重置表单
    resetForm() {
      this.materialForm = {
        page: 1,
        pageSize: 10,
        startTime: null,
        endTime: null,
        status: null,
        type: null,
        operatorId: "",
        userId: this.$store.getters.userId,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
/* 添加这些样式到style部分 */
.goods-table-container {
  width: 100%;
  margin-bottom: 10px;
}

.add-goods-btn {
  margin-top: 10px;
  text-align: center;
}

.mb-0 {
  margin-bottom: 0;
}

/* 确保表单验证错误消息正确显示 */
.el-table .el-form-item {
  margin-bottom: 0;
}

.el-form-item ::v-deep .el-form-item__error {
  position: static;
  padding-top: 4px;
}

.goods-detail-header {
  margin-bottom: 10px;
}

.pagination-container {
  text-align: right;
}

/* 自定义下划线 */
.custom-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 13px 0;
}

/* 商品明细样式 */
.goods-detail-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  text-align: left;
  padding: 5px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.goods-name {
  width: 150px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 10px;
}

.goods-number {
  width: 100px;
  color: #606266;
}

.number-value {
  color: #409eff;
  font-weight: 500;
}

.no-goods {
  color: #909399;
  padding: 10px 0;
}
</style>
